package com.sxt.practiceapplication.activities;


import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.contract.ActivityResultContracts;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.callback.StringCallback;
import com.sxt.practiceapplication.base.BaseActivity;
import com.sxt.practiceapplication.common.ServerStatus;
import com.sxt.practiceapplication.common.Urls;
import com.sxt.practiceapplication.databinding.ActivityLoginBinding;
import com.sxt.practiceapplication.entity.user.LoginData;
import com.sxt.practiceapplication.entity.user.data.LoginResultData;
import com.sxt.practiceapplication.utils.GsonBinder;
import com.sxt.practiceapplication.utils.LoginUser;
import com.sxt.practiceapplication.utils.Tools;

import okhttp3.Call;
import okhttp3.Response;

public class LoginActivity extends BaseActivity {

    public static final int REGISTER_RESULT_CODE = 1;

    private ActivityLoginBinding activityLoginBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityLoginBinding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(activityLoginBinding.getRoot());
        initView();
    }

    private void initView() {
        // 点击前往注册页面
        setClickToRegister();

        // 登录逻辑
        setLogin();
    }

    private void setLogin() {
        activityLoginBinding.buttonLogin.setOnClickListener(v -> {
            String account = activityLoginBinding.account.getText().toString();
            String password = activityLoginBinding.password.getText().toString();
            if (!(account.length() >= 2 && account.length() <= 20)) {
                Tools.showEnsureDialog(LoginActivity.this, "操作提示", "账号长度应在2-20之间");
            } else if (!(password.length() >= 6 && password.length() <= 20)) {
                Tools.showEnsureDialog(LoginActivity.this, "操作提示", "密码长度应在6-20之间");
            } else {
                doLogin(account, password);
            }
        });
    }

    private void doLogin(String account, String password) {
        OkHttpUtils.post(Urls.LOGIN_URL)
                .tag(this)
                .cacheMode(CacheMode.NO_CACHE)
                .params("username", account)
                .params("password", password)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {
                        LoginResultData loginResult = GsonBinder.toObj(result, LoginResultData.class);
                        if (loginResult.getCode().equals(ServerStatus.SUCCESS.getCode())) {
                            LoginData loginResultData = loginResult.getData();
                            LoginUser.login(LoginActivity.this, loginResultData.getToken(), loginResultData.getUserId());
                            redirectOnLoginSuccessful();
                        } else {
                            Tools.showEnsureDialog(LoginActivity.this, "登录失败", loginResult.getMessage());
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        Tools.showErrorDialog(LoginActivity.this, "服务器错误");
                    }
                });
    }

    private void redirectOnLoginSuccessful() {
        Intent target = getIntent().getParcelableExtra("target");
        if (target != null) {
            startActivity(target);
        }
        finish();
    }

    private void setClickToRegister() {
        activityLoginBinding.toRegister.setOnClickListener(v -> registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(), result -> {
                    Intent data = result.getData();
                    int resultCode = result.getResultCode();
                    if (resultCode == REGISTER_RESULT_CODE) {
                        if (data != null) {
                            String username = data.getStringExtra("username");
                            String password = data.getStringExtra("password");
                            activityLoginBinding.account.setText(username);
                            activityLoginBinding.password.setText(password);
                        }
                    }
                }).launch(new Intent(new Intent(this, RegisterActivity.class))));
    }

    @Override
    protected void exitActivity() {
        finish();
    }
}